package com.zhengdongzulin.zuke.ext

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow


fun ViewGroup.inflate(layoutRes: Int): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, false)
}

fun View.setClickFinish() {
    this.setOnClickListener { (context as Activity).finish() }
}

fun PopupWindow.ShowDown(anchor: View) {
    var rect = Rect()
    anchor.getGlobalVisibleRect(rect)
    var h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom
//    var a = getNavigationHeight(context = contentView.context)
//    setHeight(h + a)
    setHeight(h)
    showAsDropDown(anchor)
}

fun getNavigationHeight(context: Context): Int {
    var resourceId = 0
    val rid = context.resources.getIdentifier("config_showNavigationBar", "bool", "android")
    return if (rid != 0) {
        resourceId = context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
        context.resources.getDimensionPixelSize(resourceId)
    } else {
        0
    }
}

fun View.transViewToBitmap( width: Int = 30,heigiht: Int = 30): Bitmap {
    val measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
    val measuredHeight = View.MeasureSpec.makeMeasureSpec(heigiht, View.MeasureSpec.EXACTLY)
    this.measure(measuredWidth, measuredHeight)
    val w = this.measuredWidth
    val h = this.measuredHeight
    val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bmp)
    canvas.drawColor(Color.TRANSPARENT) //如果不设置canvas画布为白色，则生成透明
    this.layout(0, 0, w, h)
    this.draw(canvas)
    return bmp
}

